package com.gyms.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.classic.okhttp.AppChangeUtils;
import com.gyms.R;
import com.gyms.bean.LocationBean;
import com.gyms.manager.DataCenter;
import com.gyms.manager.LocationManger;
import com.gyms.manager.ShowLacationManger;
import com.gyms.manager.StatisticsManager;
import com.orhanobut.logger.Logger;

import utils.DataUtil;
import utils.StringUtils;

/**
 * 启动页
 * ltx
 */

public class WelcomActivity extends AppCompatActivity {
    private ImageView mIvFirst;//启动页
    //定位相关
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();

    private LocationManger mLocationManger;
    private final static int WELCOM_IMG_RES=AppChangeUtils.isGymApp?R.mipmap.hl_gym_welcom:R.mipmap.hl_cgt_welcom;//区分呼啦场馆和场馆通
    //扫码启动app相关
    private Uri mUri;

    private static final int S_REQUEST_LOCATION=1;



    private Handler hander = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (null == mUri) {
//                startActivity(MainActivity.class, true);
                Intent mIntent=new Intent(WelcomActivity.this,MainActivity.class);
                startActivity(mIntent);
                finish();
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            } else {
                Intent mIntent=new Intent(WelcomActivity.this,MainActivity.class);
                Bundle mBundle = new Bundle();
                mBundle.putParcelable("key_uri", mUri);
                mIntent.putExtras(mBundle);
                startActivity(mIntent);
                finish();
//                startActivity(MainActivity.class, mBundle, true);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            //完美解决：APP下载安装后，点击“直接打开”，启动应用后，按下HOME键，再次点击桌面上的应用，会重启一个新的应用问题
            finish();
            return;
        }
        doInitView();
    }

    private void doInitView() {
        setContentView(R.layout.activity_welcom);
        mIvFirst= (ImageView) findViewById(R.id.iv_first);
        mLocationManger = LocationManger.getInstance(getApplicationContext());
        initLocation();
        doCheckPermission();
        mUri=getIntent().getData();
        showWelcome();
    }

    private void doCheckPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {//没权限
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, S_REQUEST_LOCATION);//自定义的code
        }else{//有这权限
            startLocation();
        }

    }

    /**
     * 显示启动页
     */

    private void showWelcome() {
        mIvFirst.setVisibility(View.VISIBLE);
        mIvFirst.setImageResource(WELCOM_IMG_RES);
        mIvFirst.setScaleType(ImageView.ScaleType.FIT_XY);
        String token = DataUtil.getSharePre(WelcomActivity.this, "token");
        if (!StringUtils.isNull(token)) {
            DataCenter.getInstance().setToken(token);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 开始定位
     *
     * @since 2.8.0
     */
    private void startLocation() {
        //根据控件的选择，重新设置定位参数
        resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    // 根据控件的选择，重新设置定位参数
    private void resetOption() {
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);
        /*
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(false);
        locationOption.setOnceLocation(true);
        // 设置是否开启缓存
        locationOption.setLocationCacheEnable(true);
        //设置是否等待设备wifi刷新，如果设置为true,会自动变为单次定位，持续定位时不要使用
        locationOption.setOnceLocationLatest(false);
        try {
            // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
            locationOption.setInterval(Long.valueOf("1000"));
        } catch (Throwable e) {
            e.printStackTrace();
        }

        try {
            // 设置网络请求超时时间
            locationOption.setHttpTimeOut(Long.valueOf("1000"));
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化定位
     *
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    LocationBean mLocationBean = new LocationBean(amapLocation);
                    String result = ShowLacationManger.getLocationStr(amapLocation);
                    Logger.i(result);
                    DataCenter.getInstance().setLocationBean(mLocationBean);
                    mLocationManger.mLocationBean = mLocationBean;//定位成功设置定位bean
                    mLocationManger.latitude = mLocationBean.getLatitude();
                    mLocationManger.longitude = mLocationBean.getLongitude();
                    mLocationManger.setDetaiAddress(mLocationBean.getAddress());
                    mLocationManger.setAdCode(mLocationBean.getAdCode());
                } else {
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
            hander.sendMessageDelayed(new Message(), 2000);//停止两秒跳首页
            destroyLocation();
        }
    };

    /**
     * 默认的定位参数
     *
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
       /* mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒*/
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是ture
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        return mOption;
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /*
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatisticsManager.startActivity(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatisticsManager.endActivity(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
        switch (requestCode){
            case S_REQUEST_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startLocation();
                } else {
                    hander.sendMessageDelayed(new Message(), 2000);//停止两秒跳首页
                }
                break;
        }
    }
}
